package com.pu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pu.constant.MessageConstant;
import com.pu.dto.UserLoginDTO;
import com.pu.entity.User;
import com.pu.exception.LoginFailedException;
import com.pu.mapper.UserMapper;
import com.pu.properties.WeChatProperties;
import com.pu.service.UserService;
import com.pu.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author Yusc
 * @Date 2023/10/31 14:25
 * @Version
 * @Description C端用户管理
 **/
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    //https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * @param userLoginDTO
     * @auther: Yusc
     * @date 2023/10/31 14:25
     * @Description 微信登录
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //1、判断openid是否为空，如果为空表示登录失败，抛出业务异常
        String openid = getOpenid(userLoginDTO.getCode());
        //2、判断当前用户是否为新用户
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        User user = userMapper.getByOpenid(openid);
        //3、判断当前用户是否为新用户
        if (user == null) {
            //4、如果是新用户，自动完成注册
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();

            userMapper.insert(user);
        }
        //5、返回这个用户对象
        return user;
    }

    /**
     * @param code C端用户登录授权码
     * @return openid
     * @auther: Yusc
     * @date 2023/10/31 16:04
     * @Description 调用微信接口服务，获取微信用户的openid
     */
    private String getOpenid(String code) {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        return jsonObject.getString("openid");
    }
}

